import {
    REMOVE,
    ATTR,
    SPLICE,
    TEXT
} from './patchesType';
let patches = {};
let vnIndex = 0;

function domDiff(oldVDom, newVDom) {
    let index = 0;
    vNodeWalk(oldVDom, newVDom, index);
    return patches;
}

function vNodeWalk(oldNode, newNode, index) {
    const patchesItem = []; // 每一项补丁包

    // 新节点没有
    if (!newNode) {
        patchesItem.push({
            type: REMOVE,
            index,
        });
    } else if(typeof oldNode === 'string' && typeof newNode === 'string'){
        // 新节点为文本节点
        if(newNode!==oldNode){
            patchesItem.push({
                type:TEXT,
                text:newNode,
            })
        }
    } else if (oldNode.type === newNode.type) {
        // 新节点与老节点的类型相同判断属性
        const attrPatchs = attrWalk(oldNode.props,newNode.props);
        if(Object.keys(attrPatchs).length>0){
            patchesItem.push({
                type:ATTR,
                attr:attrPatchs,
            });
        }
        // 判断下面的子级  进行递归操作
        childrenWalk(oldNode.children,newNode.children);
    }else {
        // dom的替换操作
        patchesItem.push({
            type:SPLICE,
            newNode,
        });
        // 判断下面的子级  进行递归操作
        childrenWalk(oldNode.children,newNode.children);
    }

    if(patchesItem.length>0){
        // 最后把每个类型的补丁打到总补丁对象中
        patches[index] = patchesItem;
    }
}

function attrWalk(oldAttrs,newAttrs){
    let attrPatchs = {};
    // 修改属性
    for (let key in oldAttrs) {
        if (oldAttrs[key] !== newAttrs[key]) {
            attrPatchs[key] = newAttrs[key];
        }
    }
    // 增加属性
    for (let key in newAttrs) {
        if (!oldAttrs[key]) {
            attrPatchs[key] = newAttrs[key];
        }
    }
    return attrPatchs;
}

function childrenWalk(oldChildren=[],newChildren=[]){
    oldChildren.map((child,index)=>{
        vNodeWalk(child,newChildren[index],++vnIndex);
    })
}
export default domDiff;